package com.baidu.ota.presenter;

import android.os.Handler;
import android.text.TextUtils;

import com.baidu.commonlib.interfaces.ErrorCode;
import com.baidu.commonlib.interfaces.ICheckUpdateListener;
import com.baidu.commonlib.interfaces.IOtaAgent;
import com.baidu.ota.R;
import com.baidu.ota.model.IOtaModel;
import com.baidu.ota.model.OtaModelImpl;
import com.baidu.ota.view.ICheckView;

import org.json.JSONArray;
import org.json.JSONObject;

public class CheckPresenterImpl implements ICheckPresenter {
    private long startTime = 0;

    private final IOtaModel model;
    private final ICheckView view;
    private final Handler handler;

    private static final String SYS_OTA = "com.android.system";
    private final String targetPkgName;

    CheckPresenterImpl(IOtaAgent agent, ICheckView view, boolean system) {
        this.model = new OtaModelImpl(agent);
        this.handler = new Handler();
        this.view = view;

        this.targetPkgName = system ? SYS_OTA : "";
    }

    @Override
    public void checkUpdate() {
        startTime = System.currentTimeMillis();

        view.showProgressText(view.getContext().getString(R.string.checking_for_updates));

        model.checkUpdate(new CheckListener(view));
    }

    private void waitFor(final Runnable runnable) {
        final long diff = System.currentTimeMillis() - startTime;
        long wait = diff < 1000 ? 1000 - diff : 0;
        handler.postDelayed(runnable, wait);
    }

    private class CheckListener implements ICheckUpdateListener {
        private final ICheckView view;

        CheckListener(ICheckView v) {
            view = v;
        }

        @Override
        public void onSuccess(String updateInfo) {
            String pkgName = null;
            String info = null;
            String version = null;
            try {
                JSONArray array = new JSONArray(updateInfo);
                for (int i = 0; i < array.length(); ++i) {
                    final JSONObject object = array.getJSONObject(i);
                    String pkg = object.optString("package");
                    info = object.optString("info");
                    version = object.getString("version");
                    if (TextUtils.isEmpty(targetPkgName) && !pkg.equals(SYS_OTA)) {
                        pkgName = pkg;
                        break;
                    } else if (pkg.equals(targetPkgName)) {
                        pkgName = pkg;
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            final String finalResObject = pkgName;
            final String finalInfo = info;
            final String finalVersion = version;
            waitFor(new Runnable() {
                @Override
                public void run() {
                    if (TextUtils.isEmpty(finalResObject)) {
                        view.onCheckFailResult(ErrorCode.CHECK_NO_UPDATE, "no response");
                    } else {
                        view.onCheckSuccessResult(finalResObject, finalInfo, finalVersion);
                    }
                }
            });
        }

        @Override
        public void onFail(final int code, final String reason) {
            waitFor(new Runnable() {
                @Override
                public void run() {
                    view.onCheckFailResult(code, reason);
                }
            });
        }
    }
}
